'use strict';

const cluster = require('cluster');
const express = require('express');
const { get } = require('lodash');
const socket = require('./app/socket');
const router = require('./app/router');
const { getConfig } = require('./app/utils');
const { logger } = require('./app/misc/logger');
const ErrorHandle = require('./app/middleware/error-handle');

// 全局异常处理
process.on('unhandledRejection', (reason, p) => {
	logger.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
	// application specific logging, throwing an error, or other logic here
});

process.on('uncaughtException', function (err) {
	logger.log('Caught exception: ', err);
});

if (cluster.isMaster) {
	const config = getConfig();
	logger.log(`Master pid ${process.pid} is running`);

	if (get(config, 'server') && get(config, 'id')) {
		// init web - socket connect
		socket.connect();
	}

	cluster.on('exit', function (deadWorker, code, signal) {
		logger.log('------ cluster on exit event ------');
		// Restart the worker
		const worker = cluster.fork();

		// Note the process IDs
		const newPID = worker.process.pid;
		const oldPID = deadWorker.process.pid;

		// Log the event
		logger.log(`worker pid ${oldPID} died.`);
		logger.log(`worker pid ${newPID} born.`);
	});

	for (let i = 0; i < 2; i++) {
		const worker = cluster.fork();
	}
} else {
	const config = getConfig();
	if (get(config, 'NODE_DEBUG', false)) {
		process.env.NODE_DEBUG = true;
	}

	logger.log(`Worker pid ${process.pid} is running, worker.id: ${cluster.worker.id}`);

	const app = express();
	app.use(express.urlencoded({ extended: false }));
	app.use(express.json());

	// 扩展 res.send() 方法
	app.response.sendOk = function sendOk(data) {
		// code is intentionally kept simple for demonstration purpose
		return this.send({
			errCode: 0,
			errMsg: 'request:ok',
			data
		});
	};

	app.use(router);
	app.use(ErrorHandle);

	const port = process.env.PORT || get(config, 'port') || 9001
	app.listen(port, () => {
		logger.log(`Http Server is running at http://localhost:${port}`);
	});
}
